import 'package:get/get.dart';
import 'package:jiffy/jiffy.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/model/abnormal_zero_record.dart';
import 'package:sgy_flutter/model/detection_result_model.dart';
import 'package:dartx/dartx.dart';
import 'package:sgy_flutter/model/hitch_record_req.dart';

enum DetectionPageState { loading, error, notSupport, success }

class DetectionLogic extends GetxController {
  Rx<DetectionPageState> state = DetectionPageState.success.obs;

  Rxn<DetectionResultModel> resultModel = Rxn();
  Rxn<AbnormalZeroRecord> zeroRecord = Rxn();
  Rxn<String> firmware = Rxn("");

  Rxn<DetectionResultModel> resultModelRight = Rxn();
  Rxn<AbnormalZeroRecord> zeroRecordRight = Rxn();
  Rxn<String> firmwareRight = Rxn("");

  var detectionDate = "".obs;

  @override
  void onReady() async {
    detectionDate(Jiffy.now().format(pattern: "yyyy-MM-dd HH:mm"));
    try {
      state(DetectionPageState.loading);
      if (bleManager.deviceModel?.isDoubleSlide == true || rightBleManager.deviceModel?.isDoubleSlide == true) {
        if (!bleManager.isReady.value && !rightBleManager.isReady.value){
          await bleManager.ensureDeviceConnected();
        }
        try{
          await detectionManager(bleManager, resultModel: resultModel,
              zeroRecord: zeroRecord,
              firmware: firmware);
        }catch(e){
          printError(info: "$e");
        }
        try{
          await detectionManager(rightBleManager, resultModel: resultModelRight,
              zeroRecord: zeroRecordRight,
              firmware: firmwareRight);
        }catch(e){
          printError(info: "$e");
        }
      }else{
        if (await bleManager.ensureDeviceConnected()){
          await detectionManager(bleManager, resultModel: resultModel,
              zeroRecord: zeroRecord,
              firmware: firmware);
        }
      }
      state(DetectionPageState.success);
    } catch (e) {
      state(DetectionPageState.error);
    }

    super.onReady();
  }

  Future detectionManager(BleManager manager,
      {required Rxn<DetectionResultModel> resultModel,
        required Rxn<AbnormalZeroRecord> zeroRecord,
        required Rxn<String> firmware}) async {
    final resp = await manager.detection();
    resultModel(resp);
    final deviceInfo = await manager.deviceInfoService.readDeviceInfo();
    firmware(deviceInfo.firmwareRevision);
    //零点异常后面加的,没有的话就不显示
    try {
      final zeroResp = await manager.fetchAbnormalZeroRecord();
      zeroRecord(zeroResp);
    } catch (e) {
      printInfo(info: "获取异常零点失败:$e");
    }

    try {
      final hitchResp = await apiService.checkHitch(
          productSn: manager.deviceModel?.deviceSN,
          deviceId: manager.deviceModel?.deviceID);
      if (hitchResp.isSuccess) {
        final hitchData = hitchResp.data;
        if (hitchData != null && hitchData.isFixed == false &&
            hitchData.needToWrite == true) {
          final scaleFactor = hitchData.scaleFactor;
          if (scaleFactor != null) {
            final byteArray = scaleFactor.characters.chunked(2).map((e) =>
                e.join().toInt(radix: 16)).toList();
            await manager.customService.fixHitch(byteArray);
            final checkByteArray = await manager.customService.checkHitch();
            if (checkByteArray.contentEquals(byteArray)) {
              apiService.fixHitch(id: hitchData.id);
            }
          }
        }
      }
    } catch (e) {
      printError(info: "$e");
    }

    try {
      final req = HitchRecordReq(productSn: manager.deviceModel?.deviceSN,
          deviceId: manager.deviceModel?.deviceID,
          firmware: manager.deviceModel?.firmware,
          hardware: manager.deviceModel?.hardware,
          detectionData: resp.toString(),
          deviceType: manager.deviceModel?.deviceType.prefix);
      await apiService.uploadHitchRecord(req: req);
    } catch (e) {
      printError(info: "$e");
    }
  }


}
